package com.bw.auth.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.auth.feign.RemoteAdminService;
import com.bw.auth.service.AuthService;
import com.bw.common.constants.JwtConstants;
import com.bw.common.constants.TokenConstants;
import com.bw.common.domain.Admin;
import com.bw.common.domain.response.AdminResponse;
import com.bw.common.result.Result;
import com.bw.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;

/**
 * @Author：HaoYunde
 * @Package：com.bw.auth.service.impl
 * @Project：hyd-boot
 * @name：AuthServiceImpl
 * @Date：2024/6/17 9:00
 */
@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    public StringRedisTemplate redisTemplate;
    @Autowired
    public RemoteAdminService remoteAdminService;
    @Autowired
    private HttpServletRequest request;
    @Override
    public Result<AdminResponse> dologin(Admin admin) {
        String adminPwd = admin.getAdminPwd();
        String adminName = admin.getAdminName();
        if(adminName==null){
            return Result.error("用户名不能为空");
        }
        if(adminPwd==null){
            return Result.error("用户名不能为空");
        }
        Result<Admin> adminByadminPhone = remoteAdminService.findAdminByadminPhone(adminName);
        Admin data = adminByadminPhone.getData();
        if(data==null){
            return Result.error("请先注册");
        }
        if(!data.getAdminPwd().equals(adminPwd)){
            return Result.error("密码错误");
        }
        HashMap<String, Object> map = new HashMap<>();
        String s = UUID.randomUUID().toString().replaceAll("-", "");
        map.put(s, JwtConstants.USER_KEY);
        String token = JwtUtils.createToken(map);
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+token,
                JSON.toJSONString(data));
        AdminResponse adminResponse = new AdminResponse();
        adminResponse.setTokenTime("30MINS");
        adminResponse.setToken(token);
        return Result.success(adminResponse);
    }

    @Override
    public Result<Admin> info() {
        String header = request.getHeader(TokenConstants.TOKEN);
        String key = JwtUtils.getUserKey(header);
        System.out.println(key);
        String s = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + header);
        return Result.success(JSONObject.parseObject(s, Admin.class));
    }
}
